package com.platform.service;

import com.platform.dao.*;
import com.platform.entity.*;
import com.platform.params.SurveyAnswerParams;
import com.platform.params.SurveyQuestionParams;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ApiSurveyService {

    @Autowired
    ApiSurveyUserMapper apiSurveyUserMapper;

    @Autowired
    ApiSurveyQuestionMapper apiSurveyQuestionMapper;

    @Autowired
    ApiSurveyMapper apiSurveyMapper;

    @Autowired
    ApiSurveyAnswerMapper apiSurveyAnswerMapper;

    @Autowired
    ApiGoodsMapper apiGoodsMapper;

    @Autowired
    ApiTbGoodsMapper apiTbGoodsMapper;

    @Autowired
    ApiGoodsSpecificationService apiGoodsSpecificationService;

    /**
     * 新增调查表
     * @param title 调查表名称
     * @param surveyDesc 调查表描述
     * @param displayStatus 是否展示
     */
    public SurveyVo saveSurvey(String title, String surveyDesc, int displayStatus) {
        if(title == null || surveyDesc == null ||  "".equals(title) || "".equals(surveyDesc) || displayStatus == 0){
            throw new RuntimeException("插入调查表异常，参数不正确！");
        }
        SurveyVo surveyVo = new SurveyVo();
        surveyVo.setTitle(title);
        surveyVo.setSurveyDesc(surveyDesc);
        surveyVo.setDisplayStatus(displayStatus);
        apiSurveyMapper.save(surveyVo);
        return surveyVo;
    }

    /**
     * 新增问题表
     * @param questionParamsList
     * @return
     */
    public List<SurveyQuestionVo> saveSurveyQuestion(List<SurveyQuestionParams> questionParamsList) {
        if(questionParamsList == null || questionParamsList.isEmpty()){
            throw new RuntimeException("未获取到问题表参数！！");
        }
        List<SurveyQuestionVo> surveyQuestionVoList = new ArrayList<>();
        for (SurveyQuestionParams surveyQuestionParams : questionParamsList) {
            SurveyQuestionVo surveyQuestionVo = new SurveyQuestionVo();
            surveyQuestionVo.setQuestion(surveyQuestionParams.getQuestion());
            surveyQuestionVo.setAnserType(surveyQuestionParams.getAnserType());
            surveyQuestionVo.setSurveyId(surveyQuestionParams.getSurveyId());
            surveyQuestionVoList.add(surveyQuestionVo);
        }
        apiSurveyQuestionMapper.saveBatch(surveyQuestionVoList);
        return surveyQuestionVoList;
    }

    /**
     * 保存调查表答案
     * @param answerParamsList
     * @return
     */
    public List<SurveyAnswersVo> saveSurveyAnswer(List<SurveyAnswerParams> answerParamsList, UserVo loginUser) {
        if(answerParamsList == null || answerParamsList.isEmpty()){
            throw new RuntimeException("未获取到问题表参数！！");
        }
        List<SurveyAnswersVo> answersVoList = new ArrayList<>();
        for (SurveyAnswerParams surveyAnswerParams : answerParamsList) {
            SurveyAnswersVo answersVo = new SurveyAnswersVo();
            answersVo.setAnswerContent(surveyAnswerParams.getAnswerContent());
            answersVo.setQuestionId(surveyAnswerParams.getQuestionId());
            answersVo.setUserId(loginUser.getUserId());
            answersVoList.add(answersVo);
        }
        apiSurveyAnswerMapper.saveBatch(answersVoList);
        return answersVoList;
    }

    /**
     * 查询调查问卷
     * @param surveyId
     * @return
     */
    public SurveyVo getSurvey(Integer surveyId) {
        SurveyVo surveyVo = apiSurveyMapper.queryObject(surveyId);
        return surveyVo;
    }

    /**
     * 判断用户调查表是否已经填写
     * @param loginUser
     * @return
     */
    public boolean checkSurveyIsWrite(UserVo loginUser) {
        Map<String ,Object> params = new HashMap<>();
        params.put("userId",loginUser.getUserId());
        int count = apiSurveyMapper.queryTotal(params);
        if(count > 0){
            return true;
        }
        return false;
    }

    /**
     * 根据用户填写的调查表推荐套餐
     * @param loginUser
     * @return
     */
    public List<Map<String ,Object>> reconmmendCombo(UserVo loginUser) {
//        String userId = loginUser.getUserId().toString();
        String userId = "0";
        List<Map<String ,Object>> userSurveyAnswerList =  apiSurveyMapper.getUserSurveyAnswer(userId); //这里sql 查询的时候， userId写死了，固定为0， 应该有问题

        if(userSurveyAnswerList == null || userSurveyAnswerList.isEmpty()){
            return new ArrayList<>();
        }
        //拿到的userSurveyAnswerList的answer_content是多选的，对应多个回答处理
        List<Map<String ,Object>> handAnswerList = handAnswer(userSurveyAnswerList);
        //通过处理之后的回答，拿到对应的标签
        List<Map<String ,Object>> tagByHandAnswerList = apiSurveyMapper.getTagByHandAnswer(handAnswerList);
        //拿到对应的标签之后，推荐对应的套餐
        List<Map<String ,Object>> comboList = getComboByTag(tagByHandAnswerList);
        return comboList;
    }

    private List<Map<String ,Object>> getComboByTag(List<Map<String, Object>> tagByHandAnswerList) {
        String week = getWeek();
        for (Map<String, Object> map : tagByHandAnswerList) {
            if (map == null){
                tagByHandAnswerList.remove(map);
            }
        }
        List<Map<String ,Object>> comboList = apiSurveyMapper.getComboByTag(week,tagByHandAnswerList);

        //遍历套餐， 通过套餐的商品id，查找套餐包含的商品
        for (Map<String, Object> map : comboList) {
            Object id = map.get("id");
            if(null != id) {
                List<TbGoodsVo> goodsVos = apiTbGoodsMapper.queryGoodsByComboId(Integer.parseInt(id.toString()));
                map.put("goodsVo",goodsVos);
            }

        }
        return comboList;
    }

    private List<Map<String, Object>> handAnswer(List<Map<String, Object>> userSurveyAnswerList) {
        List<Map<String ,Object>> handAnswerList = new ArrayList<>();
        for (Map<String, Object> map : userSurveyAnswerList) {
            if(map.get("anser_type") != null && "2".equals(map.get("anser_type"))){  //调查表选项为多选
                String answer_content = map.get("answer_content").toString();
                String[] answer = answer_content.split(",");
                for (int i = 0; i < answer.length; i++) {
                    Map<String, Object> temp = new HashMap<>();
                    temp.put("survey_id",map.get("survey_id"));
                    temp.put("question_id",map.get("question_id"));
                    temp.put("anser_type",map.get("anser_type"));
                    temp.put("answer_content",answer[i]);
                    handAnswerList.add(temp);
                }
            }else{
                handAnswerList.add(map);
            }
        }
        return handAnswerList;
    }

    private String getWeek() {
        String week = "";
        Date today = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(today);
        int weekday = c.get(Calendar.DAY_OF_WEEK);
        if (weekday == 1) {
            week = "周日";
        } else if (weekday == 2) {
            week = "周一";
        } else if (weekday == 3) {
            week = "周二";
        } else if (weekday == 4) {
            week = "周三";
        } else if (weekday == 5) {
            week = "周四";
        } else if (weekday == 6) {
            week = "周五";
        } else if (weekday == 7) {
            week = "周六";
        }
        return week;
    }

    /**
     * 根据套餐获取详情
     */
    public List<Map<String ,Object>> getComboInfoById(Integer id) {
        List<Map<String ,Object>> resultList = new ArrayList<>();
        List<Map<String ,Object>> comboList = apiSurveyMapper.getComboById(id);
        //通过组合套餐里面的goodsid获取具体的货物
        for (Map<String, Object> map : comboList) {
            String[] goods_id = map.get("goods_id").toString().trim().replace(" ","").split(",");
            List<GoodsVo> goodsVos = apiGoodsMapper.queryAllGoodsList(goods_id);
            for (GoodsVo goodsVo : goodsVos) {
                GoodsSpecificationVo goodsSpecificationVo = apiGoodsSpecificationService.queryObject( goodsVo.getId());
                goodsVo.setGoodsSpecificationVo(goodsSpecificationVo);
            }
            map.put("goodsVo",goodsVos);
            resultList.add(map);
        }
        return resultList;
    }
}
